import time
import os
import sqlite3
import numpy as np
from tqsdk import TqApi, TqAuth, TqKq
from rich.console import Console
from rich.theme import Theme
from MyTT import REF, EMA, SUM

# 定义颜色主题
custom_theme = Theme({
    "info": "bright_cyan",
    "warning": "bright_yellow",
    "error": "bright_red",
    "success": "bright_green",
    "trade": "bold bright_magenta"
})
console = Console(theme=custom_theme)

if __name__ == "__main__":
    try:
        api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

        symbol="SHFE.ni2506"

        klines = api.get_kline_serial(symbol, 60*15, data_length=300)

        close = klines.close
        low = klines.low
        open = klines.open
        high = klines.high

        # 转换为 numpy 数组，方便使用 MyTT 计算
        close = np.array(close)
        low = np.array(low)
        open = np.array(open)
        high = np.array(high)

        Q = (3 * close + low + open + high) / 6
        # 计算操盘线
        trading_line = (26 * Q + 25 * REF(Q, 1) + 24 * REF(Q, 2) + 23 * REF(Q, 3) + 22 * REF(Q, 4) + 21 * REF(Q, 5) + 20 * REF(Q, 6) + 19 * REF(Q, 7) + 18 * REF(Q, 8) + 17 * REF(Q, 9) + 16 * REF(Q, 10) + 15 * REF(Q, 11) + 14 * REF(Q, 12) + 13 * REF(Q, 13) + 12 * REF(Q, 14) + 11 * REF(Q, 15) + 10 * REF(Q, 16) + 9 * REF(Q, 17) + 8 * REF(Q, 18) + 7 * REF(Q, 19) + 6 * REF(Q, 20) + 5 * REF(Q, 21) + 4 * REF(Q, 22) + 3 * REF(Q, 23) + 2 * REF(Q, 24) + REF(Q, 26)) / 351

        short_line = EMA(trading_line, 7)
        console.print(f"Symbol: {symbol}, 操盘线的值: {trading_line[-1]}", style="info")
        console.print(f"Symbol: {symbol}, 空头线的值: {short_line[-1]}", style="info")

        if trading_line[-1] > short_line[-1]:
            console.print(f"Symbol: {symbol}, 操盘线的值大于空头线的值", style="info")
        elif trading_line[-1] < short_line[-1]:
            console.print(f"Symbol: {symbol}, 操盘线的值小于空头线的值", style="info")
        else:
            console.print(f"Symbol: {symbol}, 操盘线的值等于空头线的值", style="info")

        api.close()
    except Exception as e:
        console.print(f"程序运行出错: {e}", style="error")